package org.ycx.doc.web.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.common.validator.NotNullValidator;
import org.ycx.common.validator.ValidationErrorToString;
import org.ycx.doc.dao.enums.GroupUsersRole;
import org.ycx.doc.dao.model.DocGroup;
import org.ycx.doc.dao.model.DocProject;
import org.ycx.doc.dto.DocUser;
import org.ycx.doc.service.IDocGroupService;
import org.ycx.upms.common.constants.SecurityConstants;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DocGroupcontroller
 * Created by yang on 2017-08-30 17:53:15.
 */
@Controller
@RequestMapping("/group")
public class DocGroupController {

    private static Logger _log = LoggerFactory.getLogger (DocGroupController.class);

    private static final String PRE = "group/";

    @Autowired
    private IDocGroupService service;

    /**
     * 首页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/index.html")
    public String indexPage(ModelMap modelMap,HttpSession session) {
        //TODO 获取当前登录人ID
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        List<DocGroup> masters = this.service.findGroupByUser (uid, GroupUsersRole.Master);
        modelMap.put ("groups", masters);
        List<DocGroup> developers = this.service.findGroupByUser (uid, GroupUsersRole.Developer);
        modelMap.put ("developers", developers);
        return PRE + "index";
    }


    @RequestMapping("/{gid}/detail.html")
    @ResponseBody
    public RespMSG groupDetail(@PathVariable("gid") Integer gid,HttpSession session) {
        RespMSG msg = new RespMSG ();
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        List<DocProject> projects = this.service.findGroupProjects (gid);
        int role = this.service.findGroupUserRole(gid,uid);
        List<DocUser> users = this.service.findGroupUser(gid);
        msg.initResp (RespCode.SUCCESS);
        Map<String,Object> data = new HashMap<String,Object> ();
        data.put ("projects",projects);
        data.put("canEdit",role);
        data.put("users",users);
        msg.setData (data);
        return msg;
    }

    @RequestMapping("/{gid}/addUser.html")
    public String addGroupUser(ModelMap mp,@PathVariable("gid") Integer gid){
        mp.put("gid",gid);
        mp.put("roles",GroupUsersRole.values ());
        return PRE+"addUser";
    }

    @RequestMapping("/{gid}/editUser.html")
    public String editGroupUser(ModelMap mp,@PathVariable("gid") Integer gid,@Param ("uid") Integer uid){
        mp.put("gid",gid);
        mp.put("roles",GroupUsersRole.values ());
        DocUser bean = this.service.findGroupUserById(gid,uid);
        return PRE+"addUser";
    }

    @RequestMapping("addUser")
    @ResponseBody
    public RespMSG addUser(String user,Integer gid,Integer role){
        RespMSG resp = new RespMSG ();
        DocUser bean = this.service.addGroupUser(user,gid,role);
        if(bean.getUid () !=null ){
            resp.initResp (RespCode.SUCCESS);
            resp.setData (bean);
        }else{
            resp.initResp (RespCode.FAIL);
        }
        return resp;
    }
    @RequestMapping("removeUser")
    @ResponseBody
    public RespMSG removeUser(Integer gid,Integer uid){
        RespMSG resp = new RespMSG ();
        int res =  this.service.removeGroupUser(uid,gid);
        if(res > 0){
            resp.initResp (RespCode.SUCCESS);
            resp.setData (uid);
        }else{
            resp.initResp (RespCode.FAIL);
        }
        return resp;
    }

    /**
     * 删除
     *
     * @return
     */
    @RequestMapping(value = "/checkUser")
    @ResponseBody
    public boolean check(String user) {
        int count = this.service.findUser(user);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }


    @RequestMapping("/{gid}.html")
    public String detailPage(ModelMap modelMap, @PathVariable("gid") Integer gid,HttpSession session) {
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        DocGroup group = this.service.selectByPrimaryKey (gid);
        int role = this.service.findGroupUserRole(gid,uid);
        modelMap.put ("group", group);
        modelMap.put("role",role);
        return PRE + "groupDetail";
    }

    /**
     * 新增页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/create.html")
    public String createPage(ModelMap modelMap) {
        return PRE + "create";
    }

    /**
     * 新增功能
     *
     * @param bean
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RespMSG create(DocGroup bean, HttpSession session) {
        RespMSG resp = new RespMSG ();
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getGroupName (), new NotNullValidator ("团队名称"))
                .on (bean.getGroupDesc (), new NotNullValidator ("描述"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            resp.initResp (RespCode.FAIL);
            resp.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
        }
        bean.setCreateTs (new Date ());
        bean.setUpdateTs (new Date ());
        bean.setCreateUid (uid);
        int count = service.createGroup (bean);
        if(count > 0){
            resp.initResp (RespCode.SUCCESS);
            resp.setData (bean);
        }else{
            resp.initResp (RespCode.FAIL);
            resp.setDesc ("操作失败");
        }
        return resp;
    }


    @RequestMapping("/list")
    @ResponseBody
    public RespMSG list(HttpSession session) {
        RespMSG msg = new RespMSG (RespCode.SUCCESS);
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        Map<String, List<DocGroup>> map = new HashMap<String, List<DocGroup>> ();
        List<DocGroup> masters = this.service.findGroupByUser (uid, GroupUsersRole.Master);
        map.put ("mine", masters);
        List<DocGroup> developers = this.service.findGroupByUser (uid, GroupUsersRole.Developer);
        List<DocGroup> guest = this.service.findGroupByUser (uid,GroupUsersRole.Guest);
        developers.addAll (guest);
        map.put ("joins", developers);
        msg.setData (map);
        return msg;
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/update/{id}.html")
    public String updatePage(@PathVariable("id") int id, ModelMap modelMap) {
        DocGroup bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        return PRE + "update";
    }

//    /**
//     * 更新页面
//     *
//     * @param id
//     * @param modelMap
//     * @return
//     */
//    @RequestMapping("/detail/{id}.html")
//    public String detailPage(@PathVariable("id") int id, ModelMap modelMap) {
//        DocGroup bean = this.service.selectByPrimaryKey (id);
//        modelMap.put ("bean", bean);
//        return PRE + "detail";
//    }

    /**
     * 更新功能
     *
     * @param id
     * @param bean
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG update(@PathVariable("id") int id, DocGroup bean, HttpSession session) {
        RespMSG msg = new RespMSG ();
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        //TODO 验证数据，验证完成，设定主键为id
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getGroupName (), new NotNullValidator ("团队名称"))
                .on (bean.getGroupDesc (), new NotNullValidator ("描述"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            msg.initResp (RespCode.FAIL);
            msg.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
        }else{
            bean.setUpdateTs (new Date ());
            bean.setUpdateUid (uid);
            int count = service.updateByPrimaryKeySelective (bean);
            msg.initResp (RespCode.SUCCESS);
            msg.setData (bean);
        }
        return msg;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG delete(@PathVariable("id") Integer id) {
        RespMSG resp = new RespMSG ();
        int count = service.delGroup(id);
        if(count > 0){
            resp.initResp (RespCode.SUCCESS);
        }else{
            resp.initResp (RespCode.FAIL);
        }
        return resp;
    }
}
